package com.handler;

import com.amazonaws.services.s3.model.*;
import com.amazonaws.services.s3.transfer.MyTransferManager;
import org.apache.commons.logging.LogFactory;

public class BucketHandler extends BaseHandler<String> {

    public BucketHandler(MyTransferManager transferManager) {
        super(transferManager);
    }

    @Override
    public void execute(String bucketName) {
        if (s3Client.doesBucketExistV2(bucketName)) { // 判断桶是否存在
            System.out.format("Bucket %s already exists.\n", bucketName);
        } else {
            try {
                s3Client.createBucket(bucketName);
                // 启动版本控制
                s3Client.setBucketVersioningConfiguration(
                        new SetBucketVersioningConfigurationRequest(bucketName,
                                new BucketVersioningConfiguration(BucketVersioningConfiguration.ENABLED)));
                // 设置安全策略
                CORSRule corsRule = new CORSRule();
                corsRule.setAllowedOrigins("*");
                corsRule.setAllowedMethods(CORSRule.AllowedMethods.GET);
                corsRule.setMaxAgeSeconds(3000);
                corsRule.setAllowedHeaders("*");
                s3Client.setBucketCrossOriginConfiguration(bucketName,
                        new BucketCrossOriginConfiguration().withRules(corsRule));

                System.out.format("Bucket %s created successfully.\n", bucketName);
            } catch (AmazonS3Exception e) {
                LogFactory.getLog(getClass()).error(null, e);
            }
        }

        // 关闭client
        transferManager.shutdownNow();

    }

}
